package com.xbongbong.crm.perform.query.list.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xbongbong.crm.abstracts.AbstractCrmListQryService;
import com.xbongbong.crm.handle.analysis.CustomerListAnalysisDataHandler;
import com.xbongbong.crm.perform.query.list.button.ArchivedTag;
import com.xbongbong.crm.perform.query.list.button.CustomerCommunicate;
import com.xbongbong.crm.perform.query.list.button.CustomerFocus;
import com.xbongbong.crm.perform.query.list.button.PublicTag;
import com.xbongbong.crm.perform.query.list.button.Remind;
import com.xbongbong.crm.service.condition.CustomerConditionServiceImpl;
import com.xbongbong.i18n.util.I18nMessageUtil;
import com.xbongbong.paas.call.AliyunCall;
import com.xbongbong.paas.call.CallCenterService;
import com.xbongbong.paas.domain.entity.ext.ConditionsEntityExt;
import com.xbongbong.paas.domain.entity.ext.PaasFormDataEntityExt;
import com.xbongbong.paas.elasticsearch.util.EsHelper;
import com.xbongbong.paas.elasticsearch.util.XbbElasticsearchRestTemplate;
import com.xbongbong.paas.enums.DelEnum;
import com.xbongbong.paas.field.FieldAttrEntity;
import com.xbongbong.paas.help.BusinessUserTeamHelp;
import com.xbongbong.paas.help.CommonHelp;
import com.xbongbong.paas.pojo.FormTitlePoJo;
import com.xbongbong.paas.pojo.SummaryDataPoJo;
import com.xbongbong.paas.pojo.dto.FormDataListDTO;
import com.xbongbong.paas.pojo.vo.PaasFormDataEsListVO;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.util.DateUtil;
import com.xbongbong.paas.toolbox.wrap.UserVO;
import com.xbongbong.paas.util.ExplainUtil;
import com.xbongbong.paas.util.ItemUtil;
import com.xbongbong.parent.abstracts.AbstractSpecialDataAnalysisHelp;
import com.xbongbong.parent.explain.HandleExplainHelp;
import com.xbongbong.parent.parse.data.FormDataListAnalysisDataHelp;
import com.xbongbong.parent.pojo.list.ConditionListPojo;
import com.xbongbong.parent.pojo.list.ConditionListResultPoJo;
import com.xbongbong.parent.pojo.list.DataAnalysisListPojo;
import com.xbongbong.parent.pojo.list.FieldListPojo;
import com.xbongbong.parent.pojo.list.PermissionListPojo;
import com.xbongbong.pro.applist.pojo.AppListPojo;
import com.xbongbong.pro.constant.I18nStringConstant;
import com.xbongbong.pro.customer.pojo.CustomerMainContactPojo;
import com.xbongbong.pro.enums.errorcodes.SystemErrorCodeEnum;
import com.xbongbong.pro.enums.permission.enums.ProPermissionAliasEnum;
import com.xbongbong.pro.formexplain.pojo.HandleExplainPojo;
import com.xbongbong.pro.formexplain.pojo.dto.HandlerExplainDTO;
import com.xbongbong.pro.formexplain.pojo.vo.HandlerExplainVO;
import com.xbongbong.pro.message.model.PushModel;
import com.xbongbong.saas.constant.BasicConstant;
import com.xbongbong.saas.constant.StringConstant;
import com.xbongbong.saas.domain.entity.TagLinkEntity;
import com.xbongbong.saas.enums.FormConfigEnum;
import com.xbongbong.saas.enums.SaasSpecialListEnum;
import com.xbongbong.saas.enums.TagEnum;
import com.xbongbong.saas.enums.XbbRefTypeEnum;
import com.xbongbong.saas.enums.business.CustomerManagementEnum;
import com.xbongbong.saas.help.MarketManagementBusinessHelp;
import com.xbongbong.saas.help.StageHelp;
import com.xbongbong.saas.model.CustomerFocusModel;
import com.xbongbong.saas.model.ScoreRangeModel;
import com.xbongbong.saas.model.ScoreRuleModel;
import com.xbongbong.saas.model.TagLinkModel;
import com.xbongbong.saas.service.toolbox.help.SaasListDataPermissionHelp;
import com.xbongbong.saas.toolbox.help.FastJsonHelper;
import com.xbongbong.sys.model.CompanyConfigModel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;

/**
 * @author 吴峰
 * @date 2021/12/16 13:52
 */
@Service("customerListServiceImpl")
public class CustomerListServiceImpl extends AbstractCrmListQryService {

    private static final Logger LOGGER = LoggerFactory.getLogger(CustomerListServiceImpl.class);


    @Resource
    private ScoreRangeModel scoreRangeModel;
    @Resource
    private SaasListDataPermissionHelp saasListDataPermissionHelp;
    @Resource
    private HandleExplainHelp handleExplainHelp;
    @Resource
    private CustomerListAnalysisDataHandler customerListAnalysisDataHandler;
    @Resource
    private CallCenterService callCenterService;
    @Resource
    private BusinessUserTeamHelp businessUserTeamHelp;
    @Resource
    private XbbElasticsearchRestTemplate xbbElasticsearchRestTemplate;
    @Resource
    private TagLinkModel tagLinkModel;
    @Resource
    private CompanyConfigModel companyConfigModel;
    @Resource
    private CustomerFocusModel customerFocusModel;
    @Resource
    private PushModel pushModel;
    @Resource
    @Lazy
    private Map<String, AbstractSpecialDataAnalysisHelp> webDataAnalysisHandleMap;
    @Resource
    private ScoreRuleModel scoreRuleModel;
    @Resource
    private MarketManagementBusinessHelp marketManagementBusinessHelp;
    @Resource
    private EsHelper esHelp;
    @Resource
    private CustomerConditionServiceImpl customerConditionService;
    @Resource
    private StageHelp stageHelp;
    @Resource
    private FormDataListAnalysisDataHelp formDataListAnalysisDataHelp;
    @Resource
    private Remind remind;
    @Resource
    private CustomerCommunicate customerCommunicate;
    @Resource
    private PublicTag publicTag;
    @Resource
    private AliyunCall aliyunCall;
    @Resource
    private CustomerFocus customerFocus;

    @Override
    public List<Integer> businessType() {
        return Collections.singletonList(XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode());
    }

    @Override
    public List<ConditionsEntityExt> getPermission(PermissionListPojo permissionListPojo) throws XbbException {
        UserVO userVO = permissionListPojo.getUserVO();
        List<ConditionsEntityExt> conditionList = new ArrayList<>();
        if (userVO.isMaxDataPermission()){
            return conditionList;
        }
        Integer subBusinessType = permissionListPojo.getSubBusinessType();

        if (Objects.equals(subBusinessType, XbbRefTypeEnum.CUSTOMER_PUBLIC.getCode()) || Objects.equals(subBusinessType,XbbRefTypeEnum.CUSTOMER_RECYCLE.getCode())){
            return conditionList;
        }


        return getTeamUserPermission(userVO);
    }

    @Override
    public ConditionListResultPoJo getCondition(ConditionListPojo conditionListPojo) throws XbbException {
        try {
            String corpid = conditionListPojo.getCorpid();
            Long formId = conditionListPojo.getFormId();
            List<ConditionsEntityExt> conditions = conditionListPojo.getConditionList();
            // 判断客户或者线索的评分字段，可抽离
            scoreRangeModel.scoreCondition(corpid, conditions, formId);
            // pc端 com.xbongbong.saas.help.SaasListHelp.commonFilter
            webCommonFilter(conditionListPojo);
            // 公共条件封装
            commonCondition(conditionListPojo);
            return new ConditionListResultPoJo(conditionListPojo.getConditionList(), conditionListPojo.getShouldConditionList());
        } catch (Exception e) {
            LOGGER.error("com.xbongbong.crm.list.CustomerListServiceImpl.getCondition error", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001);
        }
    }


    @Override
    public ConditionListResultPoJo mobileGetCondition(ConditionListPojo conditionListPojo) throws XbbException {
        try {
            String corpid = conditionListPojo.getCorpid();
            Long formId = conditionListPojo.getFormId();
            List<ConditionsEntityExt> conditions = conditionListPojo.getConditionList();
            // 判断客户或者线索的评分字段，可抽离
            scoreRangeModel.scoreCondition(corpid, conditions, formId);
            //  手机端条件封装
            saasListDataPermissionHelp.dingtalkRangeScreen(conditions, conditionListPojo.getUserVO(), XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode(), conditionListPojo.getSubBusinessType(), conditionListPojo.getPlatform());
            // 公共条件封装
            commonCondition(conditionListPojo);
            return new ConditionListResultPoJo(conditionListPojo.getConditionList(), conditionListPojo.getShouldConditionList());
        } catch (Exception e) {
            LOGGER.error("com.xbongbong.crm.list.CustomerListServiceImpl.getCondition error", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001);
        }
    }

    private void commonCondition(ConditionListPojo conditionListPojo) throws XbbException {
        //  图表还有个方法 com.xbongbong.saas.service.impl.SaasListServiceImpl.handleConditionBySubBusinessType
        List<ConditionsEntityExt> conditionList = customerConditionService.handleConditionBySubBusinessType(conditionListPojo);
        conditionListPojo.getConditionList().addAll(conditionList);
        setCommonCondition(conditionListPojo);
    }

    @Override
    public HandleExplainPojo getExplain(FieldListPojo fieldListPojo) throws XbbException {
        try {
            List<String> fieldList = new ArrayList();
            List<FieldAttrEntity> explainList = commonGetExplain(fieldListPojo, fieldList);
            SaasSpecialListEnum saasSpecialListEnum = SaasSpecialListEnum.getByBusinessType(fieldListPojo.getSubBusinessType());
            Iterator<FieldAttrEntity> iterator = explainList.iterator();
            switch (saasSpecialListEnum) {
                case CUSTOMER:
                case CUSTOMER_DEAL:
                case CUSTOMER_FOLLOW:
                case CUSTOMER_FOCUS:
                    while (iterator.hasNext()) {
                        FieldAttrEntity fieldAttrEntity = iterator.next();
                        String attr = fieldAttrEntity.getAttr();
                        if (Objects.equals(attr, CustomerManagementEnum.BACK_PUBLIC_DATE.getAttr())) {
                            iterator.remove();
                            break;
                        }
                    }
                    break;
                case CUSTOMER_PUBLIC:
                    while (iterator.hasNext()) {
                        FieldAttrEntity fieldAttrEntity = iterator.next();
                        String attr = fieldAttrEntity.getAttr();
                        if (Objects.equals(attr, CustomerManagementEnum.DISTRIBUTION_DATE.getAttr()) || Objects.equals(attr, CustomerManagementEnum.COUSERID.getAttr())) {
                            iterator.remove();
                        }
                        if (Objects.equals(attr, CustomerManagementEnum.OWNER_ID.getAttr())) {
                            fieldAttrEntity.setAttrName(I18nMessageUtil.getMessage(I18nStringConstant.PRE_OWNER_ID));
                        }
                    }
                    break;
                case CUSTOMER_RECYCLE:
                    while (iterator.hasNext()) {
                        FieldAttrEntity fieldAttrEntity = iterator.next();
                        String attr = fieldAttrEntity.getAttr();
                        if (Objects.equals(attr, CustomerManagementEnum.BACK_PUBLIC_DATE.getAttr()) || Objects.equals(attr, CustomerManagementEnum.DISTRIBUTION_DATE.getAttr())
                                || Objects.equals(attr, CustomerManagementEnum.OWNER_ID.getAttr()) || Objects.equals(attr, CustomerManagementEnum.COUSERID.getAttr())) {
                            iterator.remove();
                        }
                    }
                    break;
                default:
                    break;
            }
            HandlerExplainDTO handlerExplainDTO = new HandlerExplainDTO(explainList, fieldListPojo.getForm(), fieldListPojo.getCorpid(), fieldListPojo.getUserVO().getUserId(), fieldListPojo.getUserVO(), true, fieldListPojo.getSubBusinessType());
            HandlerExplainVO handlerExplainVO = handleExplainHelp.handleExplain(handlerExplainDTO);

            HandleExplainPojo handleExplainPojo = new HandleExplainPojo();
            explainList = handlerExplainVO.getHeadList();
            handleExplainPojo.setExplainList(explainList);
            handleExplainPojo.setFieldList(fieldList);

            return handleExplainPojo;
        } catch (XbbException e) {
            throw e;
        } catch (Exception e) {
            LOGGER.error("com.xbongbong.crm.list.CustomerListServiceImpl.getExplain error", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001);
        }
    }


    @Override
    public void webOperate(DataAnalysisListPojo dataAnalysisListPojo) throws XbbException{
        String corpid = dataAnalysisListPojo.getCorpid();
        String userId = dataAnalysisListPojo.getUserId();
        Integer subBusinessType = dataAnalysisListPojo.getSubBusinessType();
        List<PaasFormDataEntityExt> dataList =dataAnalysisListPojo.getFormDataList();
        List<FieldAttrEntity> list = dataAnalysisListPojo.getExplainList();
        List<Long> dataIdIn = new ArrayList<>();
        dataList.forEach(item->{
            dataIdIn.add(item.getId());
        });
        // 关注
        CustomerFocus focusPojo = customerFocus.setFocusField( corpid, userId, dataIdIn, list, dataAnalysisListPojo.getBusinessType(), subBusinessType);
        // 提醒
        Remind remindPojo = remind.setRemindField( corpid,  dataAnalysisListPojo.getBusinessType(), subBusinessType, dataIdIn, dataAnalysisListPojo.getExplainList());
        Set<String> userIdSet = new HashSet<>();
        Map<Long, List<String>> mainUserIdIn = new HashMap<>(dataIdIn.size());
        Map<Long, List<String>> coUserIdIn = new HashMap<>(dataIdIn.size());
        Boolean isPublic = Objects.equals(XbbRefTypeEnum.CUSTOMER_PUBLIC.getCode(),subBusinessType);
        businessUserTeamHelp.getUserIdMapSetShow(userIdSet, dataIdIn, corpid, dataAnalysisListPojo.getBusinessType(), isPublic, mainUserIdIn, coUserIdIn, DelEnum.NORMAL.getDel());
        // 呼叫中心
        AliyunCall aliyunCallPojo = aliyunCall.setAliCallField( corpid, dataAnalysisListPojo.getUserVO(), dataAnalysisListPojo.getExplainList(), mainUserIdIn, coUserIdIn, dataAnalysisListPojo.getBusinessType(), subBusinessType);

        // 跟进记录
        CustomerCommunicate followUpRecordPojo = customerCommunicate.getCommunicate(dataAnalysisListPojo, ProPermissionAliasEnum.CUSTOMER_COMMUNICATE_VIEW.getAlias(), dataIdIn,  corpid, dataAnalysisListPojo.getExplainList());

        Map<String, FieldAttrEntity> explainMap = new HashMap<>(dataAnalysisListPojo.getExplainList().size());
        String field = CustomerManagementEnum.NAME.getAttr();
        ArchivedTag archivedTagPojo = new ArchivedTag(field+"Tag");
        //客户公海池不显示退字标签
        PublicTag publicTagPojo = new PublicTag();
        PublicTag transferTagPojo = new PublicTag();
        if(!Objects.equals(subBusinessType,XbbRefTypeEnum.CUSTOMER_PUBLIC.getCode())){
            publicTagPojo = publicTag.getPublicTag(field + "Tag", corpid, dataIdIn,XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode());
        }
        if (Objects.equals(subBusinessType,XbbRefTypeEnum.CUSTOMER_PUBLIC.getCode())){
            //客户公海池 “转” 字标签
            transferTagPojo = publicTag.getTransferTag(field + "Tag", corpid, dataIdIn,XbbRefTypeEnum.CUSTOMER_TRANSFER.getCode());
        }
        dataAnalysisListPojo.getExplainList().forEach(item->{
            if (Objects.equals(item.getAttr(), field)) {
                item.setTagAttr(field + "Tag");
            }
            explainMap.put(item.getAttr(), item);
        });
        Integer businessType = dataAnalysisListPojo.getBusinessType();
        PublicTag finalPublicTagPojo = publicTagPojo;
        PublicTag finalTransferTagPojo = transferTagPojo;
        dataList.forEach(item->{
            // 关注
            CustomerFocus.setFocusData(focusPojo, item);
            // 提醒
            Remind.setRemindData(remindPojo, item);
            // 呼叫中心
            aliyunCall.setCallData( aliyunCallPojo, corpid, item, explainMap, CustomerManagementEnum.PHONE.getAttr());
            // 跟进记录
            CustomerCommunicate.setCommunicateData(followUpRecordPojo, item);
            JSONObject tagData = item.getTagData();
            JSONObject data = item.getData();
            // 设置“归档”状态
            ArchivedTag.setArchivedData(archivedTagPojo, tagData, Objects.equals(businessType, XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode()) && Objects.equals(data.getInteger(CustomerManagementEnum.IS_ARCHIVED.getAttr()), 1), TagEnum.TAG_ARCHIVED);
            // “退”状态
            PublicTag.setPublicTagData(finalPublicTagPojo, item.getDataId(), tagData);
            // "转" 字标签
            PublicTag.setTransferTagData(finalTransferTagPojo,item.getDataId(),tagData);
        });
    }

    @Override
    public List<PaasFormDataEntityExt> webDataAnalysis(DataAnalysisListPojo dataAnalysisListPojo) throws XbbException{
        try {
            String corpid = dataAnalysisListPojo.getCorpid();
            List<PaasFormDataEntityExt> formDataList = dataAnalysisListPojo.getFormDataList();

            FormDataListDTO formDataListDTO = new FormDataListDTO(dataAnalysisListPojo.getCorpid(), dataAnalysisListPojo.getFormId(), dataAnalysisListPojo.getSaasMark(), dataAnalysisListPojo.getBusinessType(), dataAnalysisListPojo.getSubBusinessType(), dataAnalysisListPojo.getDistributorMark(), dataAnalysisListPojo.getUserVO(), dataAnalysisListPojo.getAnalysisAmountOfThousandBitsWithOriginalValue(), dataAnalysisListPojo.getPage(), dataAnalysisListPojo.getPageSize());
            PaasFormDataEsListVO formDataListVO = new PaasFormDataEsListVO();
            formDataListVO.setPaasFormDataESList(formDataList);
            formDataListVO.setHeadList(dataAnalysisListPojo.getExplainList());

            AbstractSpecialDataAnalysisHelp abstractSpecialDataAnalysisHelp = webDataAnalysisHandleMap.get(XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode());
            CustomerMainContactPojo customerMainContactPojo = abstractSpecialDataAnalysisHelp.getSpecialData(formDataListDTO, formDataListVO);

            Map<String, String> lastConnectTimeMap = customerMainContactPojo.getLastConnectTimeMap();
            List<Long> dataIdIn = new ArrayList<>();
            formDataListVO.getPaasFormDataESList().forEach(item->{
                dataIdIn.add(item.getId());
                // 客户的最后跟进时间
                item.getData().put(FormConfigEnum.CUSTOMER_LAST_CONNECT_TIME.getDbAlias(), lastConnectTimeMap.get(FormConfigEnum.CUSTOMER_LAST_CONNECT_TIME.getConfig()));
            });
            //设置阶段预警颜色部分数据
            stageHelp.setWarningColorData(formDataListDTO, formDataListVO.getPaasFormDataESList(), formDataListVO.getHeadList());
            customerListAnalysisDataHandler.analysisDataList(formDataListDTO, formDataListVO);
            customerListAnalysisDataHandler.analysisAmountOfThousandBits(formDataListVO, dataAnalysisListPojo.getAnalysisAmountOfThousandBitsWithOriginalValue());
            // todo 这里要优化
            for (PaasFormDataEntityExt paasFormDataEntityExt : formDataListVO.getPaasFormDataESList()) {
                formDataListAnalysisDataHelp.handleWebListScoreShowValue(XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode(), paasFormDataEntityExt);
            }


            Map<Long, List<String>> mainUserIdIn = new HashMap<>(dataIdIn.size());
            Map<Long, List<String>> coUserIdIn = new HashMap<>(dataIdIn.size());
            Boolean isPublic = Objects.equals(XbbRefTypeEnum.CUSTOMER_PUBLIC.getCode(), dataAnalysisListPojo.getSubBusinessType());

            businessUserTeamHelp.getUserIdMapSetShow(new HashSet<>(), dataIdIn, corpid, dataAnalysisListPojo.getBusinessType(), isPublic, mainUserIdIn, coUserIdIn, DelEnum.NORMAL.getDel());


            Map<String, FieldAttrEntity> explainMap = ExplainUtil.getExplainMapByList(dataAnalysisListPojo.getExplainList(), null);
            PaasFormDataEsListVO formDataEsListVO = new PaasFormDataEsListVO();
            formDataEsListVO.setExplainMap(explainMap);
            for (PaasFormDataEntityExt item : formDataListVO.getPaasFormDataESList()) {
                // 主联系人
                abstractSpecialDataAnalysisHelp.setSpecialData(item.getData(), item.getDataId(), customerMainContactPojo, formDataEsListVO, formDataListDTO.getLoginUser());
            }
            return formDataListVO.getPaasFormDataESList();
        } catch (Exception e) {
            LOGGER.error("com.xbongbong.crm.list.CustomerListServiceImpl.dataAnalysis error", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001);
        }
    }

    @Override
    public List<AppListPojo> dingtalkOperate(DataAnalysisListPojo dataAnalysisListPojo) throws XbbException {

        String corpid = dataAnalysisListPojo.getCorpid();
        String userId = dataAnalysisListPojo.getUserId();
        Integer subBusinessType = dataAnalysisListPojo.getSubBusinessType();
        List<AppListPojo> appListPojos = new ArrayList<>();

        List<PaasFormDataEntityExt> dataList =dataAnalysisListPojo.getFormDataList();
        Long formId = dataAnalysisListPojo.getFormId();
        Integer businessType = dataAnalysisListPojo.getBusinessType();
        List<FieldAttrEntity> list = dataAnalysisListPojo.getExplainList();
        List<Long> dataIdIn = new ArrayList<>();
        dataList.forEach(item->{
            dataIdIn.add(item.getId());
        });
        // 关注
        CustomerFocus focusPojo = customerFocus.setFocusField( corpid, userId, dataIdIn, list, dataAnalysisListPojo.getBusinessType(), subBusinessType);
        // 提醒
        Remind remindPojo = remind.setRemindField( corpid,  businessType, subBusinessType, dataIdIn, dataAnalysisListPojo.getExplainList());
        Set<String> userIdSet = new HashSet<>();
        Map<Long, List<String>> mainUserIdIn = new HashMap<>(dataIdIn.size());
        Map<Long, List<String>> coUserIdIn = new HashMap<>(dataIdIn.size());
        Boolean isPublic = Objects.equals(XbbRefTypeEnum.CUSTOMER_PUBLIC.getCode(),subBusinessType);
        businessUserTeamHelp.getUserIdMapSetShow(userIdSet, dataIdIn, corpid, dataAnalysisListPojo.getBusinessType(), isPublic, mainUserIdIn, coUserIdIn, DelEnum.NORMAL.getDel());
        // 呼叫中心
        AliyunCall aliyunCallPojo = aliyunCall.setAliCallField( corpid, dataAnalysisListPojo.getUserVO(), dataAnalysisListPojo.getExplainList(), mainUserIdIn, coUserIdIn, businessType, subBusinessType);

        String field = CustomerManagementEnum.NAME.getAttr();

        // 退
        PublicTag publicTagPojo = PublicTag.getTagLinkMap(tagLinkModel, field + "Tag", corpid, dataIdIn, XbbRefTypeEnum.CUSTOMER_PUBLIC.getCode());
        // “转” 字标签
        PublicTag transferTagPojo = PublicTag.getTagLinkMap(tagLinkModel, field + "Tag", corpid, dataIdIn, XbbRefTypeEnum.CUSTOMER_TRANSFER.getCode());

        HandlerExplainDTO handlerExplainDTO = new HandlerExplainDTO();
        handlerExplainDTO.setLoginUser(dataAnalysisListPojo.getUserVO());
        handlerExplainDTO.setUserId(dataAnalysisListPojo.getUserId());
        Map<String, FieldAttrEntity> explainMap = new HashMap<>(dataAnalysisListPojo.getExplainList().size());
        dataAnalysisListPojo.getExplainList().forEach(item->{
            explainMap.put(item.getAttr(), item);
        });

        for (PaasFormDataEntityExt customer : dataList) {
            JSONObject data = customer.getData();
            Long customerId = customer.getDataId();
            Long dataId = customer.getDataId();
            Long appId = customer.getAppId();
            Long menuId = customer.getMenuId();
            String name = FastJsonHelper.getStringOrDefaultFromFormData(data, CustomerManagementEnum.NAME.getAttr(), "");

            JSONObject superScript = new JSONObject();
            JSONObject others = new JSONObject();

            List<SummaryDataPoJo> lableList = FastJsonHelper.getJsonArrOrDefaultFromFormData(data, BasicConstant.LABELS_LIST, new JSONArray()).toJavaList(SummaryDataPoJo.class);
            List<SummaryDataPoJo> summaryList = FastJsonHelper.getJsonArrOrDefaultFromFormData(data, BasicConstant.SUMMARY_LIST, new JSONArray()).toJavaList(SummaryDataPoJo.class);
            List<FormTitlePoJo> titleList = FastJsonHelper.getJsonArrOrDefaultFromFormData(data, BasicConstant.TITLE_LIST, new JSONArray()).toJavaList(FormTitlePoJo.class);
            // 角标 -
            superScript.put("message", remindPojo.getList().contains(customerId) ? 1 : 0);
            //非重点客户列表，添加已关注客户标记
            if(!Objects.equals(dataAnalysisListPojo.getSubBusinessType(), XbbRefTypeEnum.CUSTOMER_FOCUS.getCode())){
                if (focusPojo.getList().contains(customerId)) {
                    superScript.put("focus", 1);
                }
            }
            // isAchived为1代表归档，2代表未归档
            if(Objects.equals(data.getInteger(CustomerManagementEnum.IS_ARCHIVED.getAttr()), 1)){
                superScript.put("archived", 1);
            }
            // 非公海池列表才显示 退字标签
            if(!Objects.equals(subBusinessType,XbbRefTypeEnum.CUSTOMER_PUBLIC.getCode()) && publicTagPojo.getTagLinkMap().containsKey(customerId)){
                superScript.put("back", publicTagPojo.getTagLinkMap().getOrDefault(customerId, new TagLinkEntity()));
            }
            // 仅公海池列表才显示 转 字标签
            if(Objects.equals(subBusinessType,XbbRefTypeEnum.CUSTOMER_PUBLIC.getCode()) && transferTagPojo.getTagLinkMap().containsKey(customerId)){
                superScript.put("transfer", transferTagPojo.getTagLinkMap().getOrDefault(customerId, new TagLinkEntity()));
            }
            Boolean activeAliyunCall = aliyunCallPojo.isAliyunCallEnable();
            boolean showAliyunCall = AliyunCall.checkShowCall(corpid, explainMap, customer);
            if(activeAliyunCall && showAliyunCall){
                superScript.put("activeAliyunCall", 1);
                //others.put("isAliyunCallCenter",  1);
            }else{
                superScript.put("activeAliyunCall", 0);
                //others.put("isAliyunCallCenter",  1);
            }

            // 附近客户加公海标签
            //其他,放入评分(在前面的查询列表时，已经处理过一次评分的值，这里直接拿出来)
            if(!marketManagementBusinessHelp.feeTypeIsStandardOrAppIsClosed(corpid) && scoreRuleModel.haveEnabledScoreRule(corpid, dataAnalysisListPojo.getFormId())){
                others.put("score",data.get(CustomerManagementEnum.SCORE.getAttr()));
            }
            //最后跟进时间
            String lastConnectTimeStr = FastJsonHelper.getStringOrDefaultFromFormData(data, CustomerManagementEnum.LAST_CONNECT_TIME.getAttr(), I18nMessageUtil.getMessage(StringConstant.NEVER_CONNECT));
            // 客户最后跟进时间格式标识
            if(Objects.nonNull(data.get(FormConfigEnum.CUSTOMER_LAST_CONNECT_TIME.getDbAlias()))){
                String lastConnectTime = data.get(FormConfigEnum.CUSTOMER_LAST_CONNECT_TIME.getDbAlias()).toString();
                if(Objects.equals(lastConnectTime, "0")){
                    Long time = Long.valueOf(lastConnectTimeStr);
                    lastConnectTimeStr = DateUtil.getString(time * 1000L, DateUtil.SDFYMDHM);
                }
            }

            // 当前数据的创建人、负责人、协同人、当前操作人
            handlerExplainDTO.setOwnerId(mainUserIdIn.get(customerId));
            handlerExplainDTO.setCoUserId(coUserIdIn.get(customerId));
            handlerExplainDTO.setCreatorId(customer.getCreatorId());
            boolean stageOpen = CommonHelp.ifStageOpen(XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode(), explainMap , handlerExplainDTO);

            if (stageOpen) {
                String customerStageStr = ItemUtil.parseItemPoJoFromFormData2String(data, CustomerManagementEnum.CUSTOMER_STAGE.getAttr(), "");
                if (!customerStageStr.isEmpty()) {
                    others.put("stage", customerStageStr);
                }
            }
            if(Objects.equals(XbbRefTypeEnum.CUSTOMER_PUBLIC.getCode(), subBusinessType)){
                others.put("isGrab",1);
            }
            boolean isShowCallCenterPhone = false;
            if (!Objects.equals(XbbRefTypeEnum.CUSTOMER_PUBLIC.getCode(), subBusinessType) || Objects.equals(XbbRefTypeEnum.CUSTOMER_DEAL.getCode(), subBusinessType)) {
                isShowCallCenterPhone = true;
            }

            AliyunCall.setCallPhone(corpid, esHelp, explainMap, customer, others);

            //others.put("isCallCenter",  aliyunCallPojo.isActiveCallEnable());
            //app系统关联数据展示需要 others 和 superScript
            data.put("others",others);
            data.put("superScript",superScript);
            String finalLastConnectTimeStr = lastConnectTimeStr;
            summaryList.forEach(item -> {
                if (Objects.equals(item.getAttr(), CustomerManagementEnum.LAST_CONNECT_TIME.getAttr())) {
                    item.setValue(Collections.singletonList(finalLastConnectTimeStr));
                } else if (Objects.equals(item.getAttr(), CustomerManagementEnum.ADDRESS.getAttr())) {
                    item.setAttrName(CustomerManagementEnum.ADDRESS.getAttrName());
                }
            });
            appListPojos.add(new AppListPojo(customerId, titleList, summaryList, superScript, lableList, others, appId, menuId, formId, name,businessType,dataId));
        }
        return appListPojos;
    }

    @Override
    public List<PaasFormDataEntityExt> dingtalkDataAnalysis(DataAnalysisListPojo dataAnalysisListPojo) throws XbbException {
        try {
            String corpid = dataAnalysisListPojo.getCorpid();
            List<PaasFormDataEntityExt> formDataList = dataAnalysisListPojo.getFormDataList();

            FormDataListDTO formDataListDTO = new FormDataListDTO(dataAnalysisListPojo.getCorpid(), dataAnalysisListPojo.getFormId(), dataAnalysisListPojo.getSaasMark(), dataAnalysisListPojo.getBusinessType(), dataAnalysisListPojo.getSubBusinessType(), dataAnalysisListPojo.getDistributorMark(), dataAnalysisListPojo.getUserVO(), dataAnalysisListPojo.getAnalysisAmountOfThousandBitsWithOriginalValue(), dataAnalysisListPojo.getPage(), dataAnalysisListPojo.getPageSize());
            PaasFormDataEsListVO formDataListVO = new PaasFormDataEsListVO();
            formDataListVO.setPaasFormDataESList(formDataList);
            formDataListVO.setHeadList(dataAnalysisListPojo.getExplainList());
            formDataListVO.setForm(dataAnalysisListPojo.getForm());
            customerListAnalysisDataHandler.analysisDataList(formDataListDTO, formDataListVO);
            customerListAnalysisDataHandler.analysisAmountOfThousandBits(formDataListVO, false);
            // 摘要和标题的封装
            formDataListVO = ExplainUtil.getValueByData(formDataListVO, formDataListDTO.getFormMap(), dataAnalysisListPojo.getFormIdAndHeadListMap());
            return formDataListVO.getPaasFormDataESList();
        } catch (Exception e) {
            LOGGER.error("com.xbongbong.crm.list.CustomerListServiceImpl.dingtalkDataAnalysis error", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001);
        }
    }

}
